<!--
 *Author：jxx
 *Contact：283591387@qq.com
 *业务请在@/extension/wms/wms.huo/so_order.jsx或so_order.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://v3.volcore.xyz/docs/view-grid、https://v3.volcore.xyz/docs/web
 -->
<template>
    <view-grid ref="grid"
               :columns="enhancedColumns"
               :detail="detail"
               :details="details"
               :editFormFields="editFormFields"
               :editFormOptions="editFormOptions"
               :searchFormFields="searchFormFields"
               :searchFormOptions="searchFormOptions"
               :table="table"
               :extend="extend"
               :onInit="onInit"
               :onInited="onInited"
               :searchBefore="searchBefore"
               :searchAfter="searchAfter"
               :addBefore="addBefore"
               :addAfter="addAfter"
               :updateBefore="updateBefore"
               :rowClick="rowClick"
               :modelOpenBefore="modelOpenBefore"
               :modelOpenAfter="modelOpenAfter">
        <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
        <template #gridHeader>
        </template>
    </view-grid>
</template>
<script setup lang="jsx">
    import extend from "@/extension/wms/wms.huo/so_order.jsx";
    import viewOptions from './so_order/options.js'
    import { ref, reactive, getCurrentInstance, watch, onMounted, computed } from "vue";
    import { pushMessage } from '@/views/index/messageBus.js'
    import { ElMessage, ElMessageBox } from 'element-plus';
    const grid = ref(null);
    const { proxy } = getCurrentInstance()
    //http请求，proxy.http.post/get
    const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())
    
    // 为已完成订单添加操作列
    const enhancedColumns = computed(() => {
        const cols = [...columns];
        // 添加操作列
        cols.push({
            field: 'actions',
            title: '操作',
            type: 'string',
            width: 120,
            align: 'center',
            fixed: 'right',
            render: (h, { row }) => {
                // 只有订单状态为3（已完成）时才显示售后按钮
                if (row.order_status === 3) {
                    return h('el-button', {
                        type: 'primary',
                        size: 'small',
                        onClick: () => handleAfterSales(row)
                    }, '售后');
                }
                return '';
            }
        });
        return cols;
    });
    
    // 处理售后按钮点击
    const handleAfterSales = async (row) => {
        try {
            await ElMessageBox.confirm(
                `是否为订单【${row.ordernoas}】创建售后服务？`,
                '售后确认',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'info'
                }
            );
            
            ElMessage.success(`订单【${row.ordernoas}】售后服务已创建！`);
            
            // TODO: 这里可以添加实际的售后处理逻辑
            // 例如：调用后端API创建售后工单
            // await proxy.http.post('/api/afterSales/create', { orderNo: row.ordernoas });
            
        } catch {
            // 用户取消
        }
    };

    let gridRef;//对应[表.jsx]文件中this.使用方式一样
    //生成对象属性初始化
    const onInit = async ($vm) => {
        gridRef = $vm;
        //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
        //更多属性见：https://v3.volcore.xyz/docs/view-grid
    }
    //生成对象属性初始化后,操作明细表配置用到
    const onInited = async () => {
    }
    // 路由携带的订单编号(用于从消息面板跳转后自动筛选)
    const routeOrderNo = ref(null);
    let routeFilterApplied = false;

    const searchBefore = async (param) => {
        // 界面查询前,可给param.wheres添加查询参数
        if (!routeFilterApplied) {
            // 从路由读取一次订单编号
            const q = proxy?.$route?.query || {};
            routeOrderNo.value = routeOrderNo.value || q.ordernoas || q.orderNo || q.no;
            if (routeOrderNo.value) {
                param.wheres = param.wheres || [];
                param.wheres.push({ name: 'ordernoas', value: routeOrderNo.value });
                routeFilterApplied = true; // 只生效一次，避免后续查询还被强制过滤
            }
        }
        return true; // 返回false，则不会执行查询
    }
    const searchAfter = async (rows, result) => {
        return true;
    }
    const addBefore = async (formData) => {
        //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
        
        console.log('=== 开始保存订单 ===');
        console.log('formData 完整结构:', JSON.stringify(formData, null, 2));
        console.log('formData 的所有键:', Object.keys(formData));
        
        // 获取实际的数据对象（可能在 mainData 中）
        const data = formData.mainData || formData;
        console.log('实际使用的数据对象:', data);

        // 打印每个字段的值与类型，便于排查
        const logField = (k, v) => console.log(`[字段] ${k}:`, v, '| 类型:', typeof v);
        logField('order_name', data.order_name);
        logField('customer_id', data.customer_id);
        logField('ordernoas', data.ordernoas);
        logField('order_status', data.order_status);
        logField('create_time', data.create_time);
        logField('shipping_address', data.shipping_address);
        logField('Num', data.Num);
        logField('unit_price', data.unit_price);
        logField('total_amount(提交前)', data.total_amount);
        
        // 前端只做基本的空值检查，具体业务验证交给后端
        console.log('✅ 前端基本检查通过，提交到后端验证');

        // 规范化与默认值处理（避免类型不匹配导致保存失败）
        data.order_name = (data.order_name || '').toString().trim();
        if (data.order_name.length > 200) data.order_name = data.order_name.slice(0, 200);

        if (data.shipping_address) {
            data.shipping_address = data.shipping_address.toString().trim();
            if (data.shipping_address.length > 500) data.shipping_address = data.shipping_address.slice(0, 500);
        }

        // 客户ID/数量/单价转为数值
        if (data.customer_id != null && data.customer_id !== '') data.customer_id = parseInt(data.customer_id);
        data.Num = parseInt(data.Num);
        data.unit_price = parseFloat(data.unit_price);

        // 订单状态默认已创建(1)
        if (!data.order_status || isNaN(data.order_status)) {
            data.order_status = 1;
        }
        
        // 去掉前端的订单编号和单价验证，交给后端统一处理

        // 计算与规范化总金额：数值类型（保留2位小数）
        const calcAmount = Number(((data.unit_price || 0) * (data.Num || 0)).toFixed(2));
        data.total_amount = calcAmount;

        // 新增时不应提交主键，确保由数据库自增生成
        if ('order_id' in data) {
            delete data.order_id;
        }
        
        // 确保total_amount字段存在（即使为空也要有这个字段）
        if (!data.hasOwnProperty('total_amount')) {
            data.total_amount = null;
        }
        
        // 如果数据在嵌套对象中，更新回去
        if (formData.mainData) {
            formData.mainData = data;
        }
        
        console.log('最终保存数据:', formData);
        console.log('单价:', data.unit_price, '数量:', data.Num, '订单金额(数值型):', data.total_amount);
        console.log('=== 准备提交到后端 ===');
        return true;
    }
    const addAfter = async (result, formData) => {
        //新建保存后
        console.log('=== 保存结果 ===');
        console.log('返回结果:', result);
        console.log('result类型:', typeof result);
        console.log('result完整对象:', JSON.stringify(result, null, 2));
        
        // 保存失败时，直接显示后端返回的错误信息（已经很简洁了）
        if (result && result.status === false) {
            console.error('❌ 保存失败:', result.message);
            // 后端已经返回简洁的错误信息，直接显示即可
            return false;
        }
        
        // 保存成功（去除弹窗提示）
        // 本地消息面板即时写入(作为SignalR的兜底)
        try {
            const data = formData?.mainData || formData || {};
            const orderNo = data.ordernoas || data.orderNo || data.no;
            const desc = `新订单【${orderNo || '-'}】已创建，商品：${data.order_name || '-'}，数量：${data.Num || '-'}，金额：${data.total_amount ?? '-'}元`;
            pushMessage({
                title: '订单创建通知',
                desc,
                date: new Date().toLocaleString(),
                type: '订单',
                tag: 'success',
                route: { path: '/so_order', query: { ordernoas: orderNo } }
            });
        } catch (e) { console.warn('写入消息面板失败', e); }
        
        // 刷新表格数据
        if (gridRef && gridRef.search) {
            console.log('刷新订单列表...');
            setTimeout(() => {
                gridRef.search();
            }, 500);
        }
        
        return true;
    }
    
    const updateBefore = async (formData) => {
        //编辑保存前formData为对象，包括明细表、删除行的Id
        return true;
    }
    const rowClick = ({ row, column, event }) => {
        //查询界面点击行事件
        // grid.value.toggleRowSelection(row); //单击行时选中当前行;
    }
    const modelOpenBefore = async (row) => {//弹出框打开后方法
        return true;//返回false，不会打开弹出框
    }
    const modelOpenAfter = async (row) => {
        //弹出框打开后方法,设置表单默认值,按钮操作等
        
        // 如果是新增操作（row为空或没有order_id），自动生成订单编号
        if (!row || !row.order_id) {
            // 默认状态：已创建(1)
            if (!editFormFields.order_status) {
                editFormFields.order_status = 1;
                console.log('默认设置订单状态为已创建(1)');
            }
            const genLocalNo = () => {
                const pad = (n) => n.toString().padStart(2, '0');
                const d = new Date();
                const yyyy = d.getFullYear();
                const mm = pad(d.getMonth() + 1);
                const dd = pad(d.getDate());
                const rand = Math.floor(Math.random() * 9000) + 1000;
                return `DD${yyyy}${mm}${dd}${rand}`;
            };
            try {
                console.log('开始生成订单编号...');
                const res = await proxy.http.get('/api/so_order/generateOrderNo');
                console.log('订单编号生成响应:', res);
                if (res && res.status && res.data) {
                    editFormFields.ordernoas = res.data;
                    console.log('订单编号已生成:', res.data);
                } else {
                    const local = genLocalNo();
                    editFormFields.ordernoas = local;
                    console.warn('生成订单编号失败，使用本地编号:', local);
                }
            } catch (error) {
                const local = genLocalNo();
                editFormFields.ordernoas = local;
                console.error('生成订单编号异常，使用本地编号:', local, error);
            }
        }
    }
    //监听表单输入，做实时计算
    //监听单价变化，自动计算总金额
    watch(() => editFormFields.unit_price, (newValue) => {
        calculateTotalAmount();
    })
    
    //监听数量变化，自动计算总金额
    watch(() => editFormFields.Num, (newValue) => {
        calculateTotalAmount();
    })
    
    //计算总金额 = 单价 × 数量
    const calculateTotalAmount = () => {
        const unitPrice = parseFloat(editFormFields.unit_price) || 0;
        const num = parseInt(editFormFields.Num) || 0;
        // 组件期望数字类型，保持为 Number，保留两位用于展示
        editFormFields.total_amount = Number((unitPrice * num).toFixed(2));
        console.log('自动计算总金额:', editFormFields.total_amount, '= 单价', unitPrice, '× 数量', num);
    }
    
    //对外暴露数据
    defineExpose({})
</script>
<style lang="less" scoped>
</style>

